package servlet.PersonServlet;

import dao.PersonDAO;
import entity.PersonBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import myUtil.personCheck;

import java.io.IOException;
import java.util.Objects;

@WebServlet("/PersonSaveServlet")
public class PersonSaveServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        String I = req.getParameter("id");
        String worknumber = req.getParameter("worknumber");
        String name = req.getParameter("name");
        String department = req.getParameter("department");
        String worktime = req.getParameter("worktime");
        String degree = req.getParameter("degree");
        String profession = req.getParameter("profession");
        String title = req.getParameter("title");
        String phonenumber = req.getParameter("phonenumber");
        String address = req.getParameter("address");
        String introduction = req.getParameter("introduction");

        PersonBean obj = new PersonBean();
        obj.setWorknumber(worknumber);
        obj.setName(name);
        obj.setPhonenumber(phonenumber);
        obj.setDepartment(department);
        obj.setWorktime(worktime);
        obj.setDegree(degree);
        obj.setProfession(profession);
        obj.setTitle(title);
        obj.setAddress(address);
        obj.setIntroduction(introduction);
        if (personCheck.checkNumber(worknumber) && personCheck.checkS(name) && personCheck.checkS(department) &&
                personCheck.checkS(degree) && personCheck.checkS(profession) && personCheck.checkS(title) && personCheck.checkPhonenumber(phonenumber)) {
            PersonDAO dao = new PersonDAO();
            if(I == null || I.isEmpty() || I.equals("0")) {
                dao.addTask(obj);
            }else{
                obj.setId(Integer.parseInt(I));
                dao.updateTask(obj);
            }
            resp.sendRedirect("PersonListServlet");
        } else {
            req.setAttribute("personBean",obj);
            if(I == null || I.isEmpty() || I.equals("0"))
                req.getRequestDispatcher("PersonEditServlet").forward(req, resp);
            else
                req.getRequestDispatcher("PersonEditServlet?id=" + I).forward(req, resp);
        }
    }
}
